package com.pan.server.impl;

import com.pan.entity.HumbleHttpRequest;
import com.pan.hendle.req.impl.HumbleHttpReqHandle;
import com.pan.hendle.req.RequestHandle;
import com.pan.hendle.resp.config.DefaultHtmlRead;

import java.io.*;
import java.net.Socket;

public class HumbleHttpServer extends BasicServer implements DefaultHtmlRead {



    public HumbleHttpServer() {
        RequestHandle reqHandle = new HumbleHttpReqHandle();
        super.setRequestHandle(reqHandle);
    }


    @Override
    public void run() {
        try {
            httpServerRun();
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    private void httpServerRun() throws Exception {

        while (true) {
            Socket acceptSocket = super.getServerSocket().accept();
            super.getSocketPool().execute(()->{
                while (true){
                    HumbleHttpRequest httpReq = (HumbleHttpRequest) super.getRequestHandle().receive(acceptSocket);
                    if (httpReq == null) {
                        //connection fail
                        //timeout error
                        //hasn't HttpMessage
                        //processing code
                        try {
                            acceptSocket.shutdownInput();
                            acceptSocket.shutdownOutput();
                            acceptSocket.close();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        return;//end this connection
                    }
                    //todo: 因该要有一个储存MyHumbleServlet容器，根据HttpReq的url转发给对应的MyHumbleServlet，MyHumbleServlet处理后，返回HttpResp
                    OutputStream outputStream = null;
                    try {
                        outputStream = acceptSocket.getOutputStream();
                        PrintWriter printWriter = new PrintWriter(outputStream);
                        BufferedReader bufferedReader =
                                new BufferedReader(new InputStreamReader(read404Html()));
                        if (bufferedReader.ready()) {
                            printWriter.println(bufferedReader.readLine());
                        }
                        printWriter.flush();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });

        }
    }
}
